package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleConfigService;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/***
 * APP文章上下架状态同步MQ监听器
 */
@Component
@Slf4j
public class ApArticleDownOrUpListener {

    @Autowired
    private ApArticleConfigService apArticleConfigService;


    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void msgRecieve(ConsumerRecord<String,String> consumerRecord){
        Optional<ConsumerRecord<String, String>> optional = Optional.ofNullable(consumerRecord);
        optional.ifPresent(x -> {
            log.info("[文章状态自动同步]开始同步。。。。。。。。。。。。");
            Map map = JSON.parseObject(x.value());
            Long articleId = Long.valueOf(map.get("articleId")+""); //APP文章ID
            Short enable = Short.valueOf(map.get("enable")+""); //自媒体文章山下架状态
            Boolean isDown = false;//未下架（已上架）
            if(enable==0){
                isDown = true;
            }

            //根据APP文章ID更新apArticleConfig的isDown
            apArticleConfigService.update(Wrappers.<ApArticleConfig>lambdaUpdate()
                    .eq(ApArticleConfig::getArticleId, articleId) //更新条件
                    .set(ApArticleConfig::getIsDown, isDown  ) //更新的列
            );

            log.info("[文章状态自动同步]同步完毕。。。。。。。。。。。。");
        });

    }
}
